;
(function () {
  window.userLists = new Vue({
    el: '#userList',
    data: {
      curPage: 1, // 当前页
      limit: 10, // 每页条数
      totalCount: 0,
      totalPage: 0,
      source: 'S', //内部组织(S)或者外部组织(D)
      userData: {},
      userData1: {}, // 用户数据
      pageLimits: [10, 15, 20], // 分页条数
      createPop: false, // 新增弹出层
      editPop: false, // 编辑弹出层
      addUser: {
        account: '',
        passwd: '',
        name: '',
        phone: '',
        email: '',
        ref_identifier: '',
        source: '#'
      }, // 新增用户信息
      editUser: {}, // 编辑用户信息
      psd: '', // 密码
      agentId: null,
      appKey: null,
      appSecret: null,
      corpConfigFlag: 'N',
      isShowQyLayer: false,
      isShowAccountLayer: false,
      isShowddBtn: true,
      isShowddFlag: true,
      creatNewmenber: false, //添加用户
      menberList: '',
      menberTypeId: '',
      allSelected: false,
      selectedList: [],
      menberitem: null,
      searchmember: '',
      setSC: false,
      wxOrdd: '', //判断类型(微信还是钉钉)
      SCtext: '', //员工还是客户
      delwarm: false, //删除提示
      delType: '', //删除类型（单个/组织）
      organizationData: '', //点击删除的组织
      bindwarm: false, //未绑定警告
      permissions: JSON.parse(window.localStorage.getItem('permissions')),
      beginTime: '',
      endTime: '',
    },
    computed: {
      memberActive() {
        return rbacVues.memberActive
      }
    },
    filters: {
      formatDate: function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      company: function (item) {
        if (!item) return '--'
        var itemArr = item.split(',')
        if (itemArr.length === 1) {
          return itemArr[0]
        }
        if (itemArr.length >= 1) {
          return itemArr[0] + '...'
        }
      },
      organization: function (item) {
        var tmpArr = [];
        if (item.length === 0) return '--'
        if (item.length !== 0) {
          for (i = 0; i < item.length; i++) {
            tmpArr.push(item[i].join(' - '));
          }
        }
        if (tmpArr.length == 1) return tmpArr[0]
        if (tmpArr.length >= 1) return tmpArr[0] + '...'
      }
    },
    created() {
      // 获取授权类型
      const oauthType = localStorage.getItem('userMes') ? JSON.parse(localStorage.getItem('userMes')).oauthType : null
      if (oauthType == 'DD_AND_WX' || oauthType == 'WX') {
        this.source = 'S'
      } else {
        this.source = 'DD'
      }
    },
    methods: {
      //高度设置
      setHeight() {
        var h = $('.cm-main-content').outerHeight(true);
        if (document.querySelector('.left-tissue')) {
          document.querySelector('.left-tissue').style.height = h + 'px';
        }
      },
      //确认更改用户类型
      sureSetSC() {
        this.setSC = false
        rbacVues.sureSetmenberType();
      },
      cancleSetSC() {
        this.setSC = false
      },
      //全选
      allSelectedfun() {
        this.allSelected = !this.allSelected
        if (this.allSelected == true) {
          this.userData1.users.forEach(item => {
            item.selected = true
            this.selectedList.push(item)
          })
          this.setselected();
          return
        }
        var noSelect = []
        this.userData1.users.forEach(item => {
          item.selected = false
          noSelect.push(item)
        })
        this.nosetselected(noSelect);
      },
      //单选
      selectItem(index) {
        this.userData1.users[index].selected = !this.userData1.users[index].selected

        if (this.userData1.users[index].selected == true) {
          this.selectedList.push(this.userData1.users[index])
          this.setselected();
          this.showAllinoc();
          return
        }
        var noSelect = []
        noSelect.push(this.userData1.users[index])
        this.nosetselected(noSelect);
        this.showAllinoc();
      },
      //单个删除
      delsingle(data) {
        var noSelect = []
        noSelect.push(data)
        this.nosetselected(noSelect);
        this.userData1.users.forEach(item => {
          if (item.id == data.id) {
            item.selected = false
          }
        })
        this.showAllinoc();
      },

      //点击删除处理
      nosetselected(noSelect) {
        noSelect.forEach(item => {
          this.selectedList.forEach((item0, index) => {
            if (item.id == item0.id) {
              this.selectedList.splice(index, 1)
            }
          })
        })
        this.showAllinoc();
      },
      // 点击添加处理
      setselected() {
        let obj = {};
        person = this.selectedList.reduce((cur, next) => {
          obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
          return cur;
        }, [])

        this.selectedList = person
        this.showAllinoc();
      },
      //全选图标是否显示
      showAllinoc() {
        for (var i = 0; i < this.userData1.users.length; i++) {
          if (this.userData1.users[i].selected == false) {
            this.allSelected = false
            return
          }
        }
        this.allSelected = true
      },
      //取消
      cancle() {
        this.creatNewmenber = false;
        this.allSelected = false;
        this.selectedList = []
        this.userData1.users.forEach(item => {
          item.selected = false
        })
      },
      // 确定添加成员
      sureAddmenber() {
        var senduserid = []
        this.selectedList.forEach(item => {
          senduserid.push(item.id)
        })
        senduserid = senduserid.join(',')
        var that = this
        hlhttp.post({
          url: 'assign_users_to_organization',
          data: {
            organization_id: rbacVues.memberOrgId,
            user_ids: senduserid
          },
          success: function (data) {
            that.cancle();
            rbacVues.getmenberType1();
          }
        });
      },
      // 确定去除成员（单一）
      suerDel() {
        this.delwarm = false
        if (this.delType == 'item') {
          var that = this
          hlhttp.delete({
            url: 'organization_user?organization_id=' + rbacVues.memberOrgId + '&user_id=' + this.menberList[this.menberitem].userId,
            success: function (res) {
              rbacVues.getmenberType1();
              that.menberitem = null
              hl.toast('删除成功')
            }
          });
          hlhttp.delete({
            url: 'organization_user?organization_id=' + rbacVues.adminOrgId + '&user_id=' + this.menberList[this.menberitem].userId,
            success: function (res) {
              rbacVues.getmenberType1();
              hl.toast('删除成功')
            }
          });

        }
        if (this.delType == 'organization') {
          var that = this
          hlhttp.delete({
            url: 'position?organization_id=' + this.organizationData.id + '&pid=' + this.organizationData.parentId,
            data: {
              organization_id: this.organizationData.id,
              pid: this.organizationData.parentId,
            },
            success: (res) => {
              rbacVues.getPidData(this.organizationData.parentId, 'del', this.organizationData.id)
              hl.toast('删除成功')
            }
          })
        }

      },
      // 添加成员前判断是否选中组织
      judeg_selected_org() {
        if (this.menberTypeId) {
          this.creatNewmenber = true
        } else {
          hl.toast('请先选中组织')
        }
      },
      //是否删除（弹框）
      clearItem(type, data) {
        if (type == 'item') {
          if (this.menberList && this.menberitem != null) {
            this.delType = type
            hllayer.confirm('确认要删除该成员吗?', () => {
              this.suerDel()
            })
          } else {
            hl.toast('请先选中组织中的成员')
          }
        }
        if (type == 'organization') {
          if (data) {
            this.delType = type
            hllayer.confirm('确认要删除该组织架构吗?', () => {
              this.suerDel()
            })
            this.organizationData = data
          }
        }
      },
      // 判断是否为钉钉
      // 权限控制
      permission: function () {
        var self = this;
        var show = function () {
          if ($('.js-state').hasClass('js-access-control') && $('.js-edit').hasClass('js-access-control')) {
            $('.js-state').parent().text('--')
          }
        }
        loginPrem.loginList(show)
      },
      // 获取用户信息  有分页
      getUserData: function () {
        var self = this;
        hlhttp.get({
          url: 'tenants/users',
          data: {
            page: self.curPage,
            limit: self.limit,
            source: self.source
          },
          success: function (data) {
            data.users.forEach(element => {
              element.selected = false
            });
            self.userData = data
            self.totalPage = data.totalPage
            self.totalCount = data.totalCount
            self.permission()
          }
        });
      },
      // 获取用户信息 无分页
      getUserData1: function () {
        var self = this;
        hlhttp.get({
          url: 'tenants/users',
          data: {
            page: 1,
            limit: 100000,
            source: self.source
          },
          success: function (data) {
            data.users.forEach(element => {
              element.selected = false
            });
            self.userData1 = data
          }
        });
      },
      // 获取查询的用户数据（无分页）
      getSearchUserData1: function () {
        var self = this;
        hlhttp.get({
          url: 'tenants/users/_search_create_time',
          data: {
            page: 1,
            limit: 10000,
            beginTime: '#',
            endTime: '#',
            key_word: self.searchmember || '#',
            source: self.source
          },
          success: function (data) {
            self.userData1 = data
          }
        });
      },
      // 获取查询的用户数据（有分页）
      getSearchUserData: function () {
        var self = this;

        hlhttp.get({
          url: 'tenants/users/_search_create_time',
          data: {
            page: self.curPage,
            limit: self.limit,
            beginTime: $('input[name=beginTime]').val() || '#',
            endTime: $('input[name=endTime]').val() || '#',
            key_word: $('.js-val-info').val() || '#',
            source: self.source
          },
          success: function (data) {
            self.userData = data
            self.totalCount = data.totalCount
            self.totalPage = data.totalPage
            self.permission()
          }
        });
      },
      // 查询
      search: function () {
        this.curPage = 1;
        this.limit = 10
        this.getSearchUserData()
      },
      // 重置
      reset: function () {
        this.curPage = 1;
        this.limit = 10
        this.beginTime = ''
        this.endTime = ''
        $('.js-val-info').val('')
        this.getUserData()
      },
      // 更换分页条数加载数据
      updateLimit: function (num) {
        this.limit = num
        this.curPage = 1
        // 通过判断是否还存在有搜索条件来对应加载不同的接口数据
        // 输入了搜索条件  调用查询接口    ---------  没有搜索条件 调用获取列表数据接口
        var beginTime = this.beginTime;
        var endTime = this.endTime;
        var keyWord = $('.js-val-info').val();
        var flag = true;
        if (beginTime || endTime || keyWord) flag = false;
        if (flag) {
          this.getUserData()
          return
        }
        this.getSearchUserData()
      },
      // 停启用状态  Y启用、N禁用
      updateState: function (val, id, i) {
        var opt, self = this;
        if (val == 'Y') opt = 'N'
        if (val == 'N') opt = 'Y'

        hlhttp.put({
          url: 'tenants/user/valid',
          data: {
            user_id: id.toString(),
            opt: opt
          },
          success: function (data) {
            self.$set(self.$data.userData.users[i], 'valid', opt)
          }
        })
      },
      // 编辑用户信息
      editUserMes: function (id) {
        var self = this;
        self.editPop = true;
        self.psd = '';
        hlhttp.get({
          url: 'tenants/user',
          data: { id: id },
          success: function (data) {
            self.editUser = data
          }
        })
      },
      confirmEditUser: function () {
        var self = this;
        var validateRes = self.validateUserForm('edit')
        if (!validateRes) {
          return false;
        }

        var data = {
          'account': self.editUser.account,
          'email': self.editUser.email || '#',
          'name': self.editUser.name,
          'phone': self.editUser.phone,
          'id': self.editUser.id,
          'ref_identifier': self.editUser.refIdentifier || '#',
          'source': '#',
        };
        // 密码没有改动则传#号
        if (self.psd) {
          data['passwd'] = self.psd
        }
        if (!self.psd) {
          $('input[name=psd]').val('******')
          data['passwd'] = '#'
        }
        hlhttp.put({
          url: 'tenants/user',
          data: data,
          success: function (data) {
            self.getUserData()
            self.editPop = false;
          }
        })
      },
      // 新增用户
      confirmCreateUser: function () {
        var self = this;
        var validateRes = self.validateUserForm('add')
        if (!validateRes) {
          return false;
        }

        hlhttp.post({
          url: 'tenants/user',
          data: self.addUser,
          success: function () {
            hl.toast('新建用户成功')
            self.getUserData()
            self.addUser = {
              account: '',
              passwd: '',
              name: '',
              phone: '',
              email: '',
              ref_identifier: '',
              source: '#'
            }
            self.createPop = false
          }
        })
      },
      closeCreatePop: function () {
        this.createPop = false;
        this.addUser = {
          account: '',
          passwd: '',
          name: '',
          phone: '',
          email: '',
          ref_identifier: '',
          source: '#'
        }
      },
      showCompanyQM: function (i, val) {
        if (val) hllayer.tips($($('.company')[i]), val)
      },
      showOrganizationQM: function (i, item) {
        var tmpArr = [];
        if (item.length === 0) return false
        if (item.length !== 0) {
          for (j = 0; j < item.length; j++) {
            tmpArr.push(item[j].join(' - '));
          }
          hllayer.tips($($('.organization')[i]), tmpArr.join(','))
        }
      },
      hideQM: function () {
        return hllayer.closeall()
      },
      validateUserForm: function (type) {
        var self = this;
        var addUser = function () {
          if (!self.addUser.account) {
            hl.toast('请填写账号')
            return false;
          }
          if (!self.addUser.passwd) {
            hl.toast('请填写密码')
            return false;
          }
          if (self.addUser.passwd.length < 6) {
            hl.toast('密码长度不能小于6个字母')
            return false;
          }
          if (!self.addUser.name) {
            hl.toast('请填写联系人')
            return false;
          }
          if (!self.addUser.phone) {
            hl.toast('请填写联系方式')
            return false;
          }
          if (self.addUser.email) {
            if (!hlValidateUtil.validateEmail(self.addUser.email)) {
              hl.toast('请填写正确的邮箱地址')
              return false;
            }
          } else {
            self.addUser.email = '#'
          }
          if (!self.addUser.ref_identifier) {
            self.addUser.ref_identifier = '#'
          }
          return true
        }

        var editUser = function () {
          if (!self.editUser.account) {
            hl.toast('请填写账号')
            return false;
          }
          if (self.psd && self.psd.length < 6) {
            hl.toast('密码长度不能小于6个字母')
            return false;
          }
          if (!self.editUser.name) {
            hl.toast('请填写联系人')
            return false;
          }
          if (!self.editUser.phone) {
            hl.toast('请填写联系方式')
            return false;
          }
          if (self.editUser.email) {
            if (!hlValidateUtil.validateEmail(self.editUser.email)) {
              hl.toast('请填写正确的邮箱地址')
              return false;
            }
          }
          if (!self.editUser.ref_identifier) {
            self.addUser.ref_identifier = '#'
          }
          return true
        }

        if (type === 'add') {
          return addUser()
        }
        if (type === 'edit') {
          return editUser()
        }
      },
      ddSynchronizeUsers: function () {
        var self = this;
        if (self.corpConfigFlag == 'Y') {
          hlhttp.post({
            url: 'tenant/corp/sync_dingding',
            success: function (data) {
              this.curPage = 1;
              this.limit = 10
              // 重刷新组织列表和成员列表
              hl.toast('同步用户成功')
              self.getUserData()
              rbacVues.getStwxddData()
            }
          })
        }
        if (self.corpConfigFlag == 'N') {
          // self.isShowQyLayer = true
          self.bindwarm = true;
        }
      },
      validateAgentId: function () {
        var self = this;
        if (!self.agentId) {
          hl.toast('请填写AgentId')
          $('.agentId-ipt').focus()
          return false;
        }
      },
      validateAppKey: function () {
        var self = this;
        if (!self.appKey) {
          hl.toast('请填写appKey')
          $('.appKey-ipt').focus()
          return false;
        }
      },
      validateCorpSecret: function () {
        var self = this;
        // 企业绑定新增了微应用 AppSecret ， 暂时不需要验证企业数据真实性
        // if (self.validateQyForm()) sendValidateRequest()

        function sendValidateRequest() {
          hlhttp.put({
            url: 'user/corp_info/_check',
            data: {
              'corp_id': self.corpId,
              'corp_secret': self.corpSecret
            },
            success: function (data) {
              hl.toast(data.appDesc)
            }
          })
        }
      },
      validateQyForm: function () {
        var self = this;
        if (!self.agentId) {
          hl.toast('请填写AgentId')
          $('.agentId-ipt').focus()
          return false;
        }
        if (!self.appKey) {
          hl.toast('请填写AppKey')
          $('.corpSecret-ipt').focus()
          return false;
        }
        if (!self.appSecret) {
          hl.toast('请填写AppSecret')
          $('.corpSecret-ipt').focus()
          return false;
        }
        return true;
      },
      // 绑定第三方企业信息
      bindQyInfo: function () {
        var self = this;
        if (!self.validateQyForm()) return false;

        hlhttp.post({
          url: 'user/corp_info/_bind',
          data: {
            'agent_id': self.agentId,
            'app_key': self.appKey,
            'corp_secret': self.appSecret
          },
          success: function (data) {
            self.isShowQyLayer = false;
            self.corpConfigFlag = 'Y'
          }
        })
      },
      confirmBindQy: function () {
        this.bindQyInfo()
      },
      closeQyLayer: function () {
        this.isShowQyLayer = false;
      },
      closeAccountLayer: function () {
        this.isShowAccountLayer = false;
      },
      // 前往绑定
      gotobind() {
        hlUrlUtil.goTo('ddTEAMconfig', {
          'ddtab': true
        })
      },
    },
    beforeMount: function () {
      this.corpConfigFlag = JSON.parse(window.localStorage.getItem('userMes')).corpConfigFlag
      this.isShowddBtn = JSON.parse(window.localStorage.getItem('userMes')).oauthType == 'WX' ? false : true
      let noShow = ['DEBI']
      if (noShow.indexOf(JSON.parse(window.localStorage.getItem('userMes')).preSysCode) > -1) {
        this.isShowddFlag = false
      }
    },
    mounted: function () {
      this.getUserData()
      this.getUserData1();
      ddAccount.init()
      $("#userList").resize(function () {
        var mainHeight = parseInt($('.cm-main-content').css('minHeight'))
        var userHeight = $('#userList').height()
        if (mainHeight > userHeight) {
          $('.userL_left-tissue').height(mainHeight)
        } else {
          $('.userL_left-tissue').height(userHeight)
        }
      });
      $('.select-ul').click(function () {
        if ($(this).find('ul').css('display') == 'block') {
          $(this).find('ul').css('display', 'none')
        } else {
          $(this).find('ul').css('display', 'block')
        }
      })
      $(window).scroll(function () {
        var scrollTop = $(this).scrollTop();
        var scrollHeight = $(document).height();
        var windowHeight = $(this).height();
        if (scrollTop + windowHeight == scrollHeight) {
          $('.setmemberType').css('bottom', '20px')
        } else {
          $('.setmemberType').css('bottom', '0px')
        }
      });
    }
  })
}())
